package com.wust.modules.online.cgform.util;

import com.wust.common.system.api.SysBaseApi;
import com.wust.common.util.SpringContextUtils;
import com.wust.modules.online.cgform.entity.OnlCgformField;
import com.wust.modules.poi.handler.impl.AbstractExcelDataHandlerDefaultImpl;
import com.wust.modules.poi.util.PoiPublicUtil;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author wanheng
 */
public class ExcelDataHandlerDefaultUtil extends AbstractExcelDataHandlerDefaultImpl {

    Map<String, OnlCgformField> onlCgformFieldMap;
    SysBaseApi sysBaseApi;
    String upLoadPath;
    String online;
    String uploadType;

    public ExcelDataHandlerDefaultUtil(List<OnlCgformField> onlCgformFieldList, String upLoadPath, String uploadType) {
        this.onlCgformFieldMap = this.getMap(onlCgformFieldList);
        this.upLoadPath = upLoadPath;
        this.online = "online";
        this.uploadType = uploadType;
        this.sysBaseApi = SpringContextUtils.getBean(SysBaseApi.class);
    }

    private Map<String, OnlCgformField> getMap(List<OnlCgformField> onlCgformFields) {
        HashMap map = new HashMap(16);

        for (OnlCgformField onlCgformField : onlCgformFields) {
            map.put(onlCgformField.getDbFieldTxt(), onlCgformField);
        }

        return map;
    }

    @Override
    public void setMapValue(Map<String, Object> map, String originKey, Object value) {
        String tableType = this.getTableType(originKey);
        if (value instanceof Double) {
            map.put(tableType, PoiPublicUtil.doubleToString((Double) value));
        } else if (value instanceof byte[]) {
            byte[] values = (byte[]) value;
            String dbPath = SqlSymbolUtil.uploadOnlineImage(values, this.upLoadPath, this.online, this.uploadType);
            if (dbPath != null) {
                map.put(tableType, dbPath);
            }
        } else {
            map.put(tableType, value == null ? "" : value.toString());
        }

    }

    private String getTableType(String originKey) {
        return this.onlCgformFieldMap.containsKey(originKey) ? "$mainTable$" +
                this.onlCgformFieldMap.get(originKey).getDbFieldName() : "$subTable$" + originKey;
    }
}
